package com.zhuoyue.common.utils;

import com.zhuoyue.common.exception.ErrorType;
import com.zhuoyue.common.exception.ZyServerException;
import org.apache.commons.collections.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
public class CodeUtil {
    public static int getCode(List<Integer> codeList, int maxCode, String message) {
        int code = 1;
        if (!CollectionUtils.isEmpty(codeList)) {
            if (codeList.size() == maxCode) {
                throw new ZyServerException(ErrorType.INVALID_PARAMS.getCode(), message + "编号最多支持" + maxCode + "个！");
            } else {
                Map<Integer, Integer> map = new HashMap<>(5);
                for (Integer c : codeList) {
                    if (null != c) {
                        map.put(c, c);
                    }
                }
                for (int i = 1; i < maxCode + 1; i++) {
                    if (null == map.get(i)) {
                        code = i;
                        break;
                    }
                }
            }
        }

        if (code < 1 || code > maxCode) {
            throw new ZyServerException(ErrorType.INVALID_PARAMS.getCode(), message + "编号错误！");
        }
        return code;
    }
}
